package com.carkeeper.order.service.impl;

import com.carkeeper.common.utils.Result;
import com.carkeeper.common.utils.StatusCode;
import com.carkeeper.order.dao.OrderDetailMapper;
import com.carkeeper.order.dao.OrderLogMapper;
import com.carkeeper.order.dao.OrderMapper;
import com.carkeeper.order.pojo.Order;
import com.carkeeper.order.pojo.OrderDetail;
import com.carkeeper.order.pojo.OrderGroup;
import com.carkeeper.order.pojo.OrderLog;
import com.carkeeper.order.service.OrderService;
import com.carkeeper.subject.feign.SubjectFeign;
import com.carkeeper.subject.pojo.Store;
import com.carkeeper.user.feign.CarFeign;
import com.carkeeper.user.pojo.Car;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CarFeign carFeign;
    @Autowired
    private SubjectFeign subjectFeign;

    //分页+条件
    @Override
    public Map findPage(Map searchMap) {
        //默认当前页
        int pageNum = 1;
        //默认每页显示条数
        int pageSize = 10;
        PageHelper.startPage(pageNum, pageSize);
/*        String startTime = (String) searchMap.get("startTime");
        String endTime = (String) searchMap.get("endTime");
        Date startTimeDate = null;
        Date endTimeDate = null;
        try {
            startTimeDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime);
            endTimeDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        searchMap.put("startTime", startTimeDate);
        searchMap.put("endTime",endTimeDate);*/
        //自定义类，封装参数
        Example example = createExample(searchMap);
        //按创建订单的时间降序
        example.orderBy("createDate").desc();

        List<Order> item = orderMapper.selectByExample(example);

        //使用PageInfo自定义参数
        PageInfo<Order> info = new PageInfo<>(item);
        //修改自定义要封装的参数
        //总条数
        long counts = info.getTotal();
        //总页数
        int pages = info.getPages();
        //把自定义的参数封装到map集合中
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("counts", counts);
        resultMap.put("pages", pages);
        resultMap.put("item", item);
        resultMap.put("page", pageNum);

        //返回map集合
        return resultMap;
    }

    /**
     * 查询所有待处理订单
     *
     * @param orderStatus
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Order> pendingAll(Map<String, Object> searchMap, int orderStatus, int page, int size) {
        PageHelper.startPage(page, size);//进行分页
        //条件判断（订单状态）
        if ((StatusCode.ORDER_STATUS_WAITING_SERVICE) == orderStatus || (StatusCode.ORDER_STATUS_WAITING_ORDER) == orderStatus) {
            Order order = new Order();
            order.setOrderStatus(orderStatus + "");
            Example example = createExample(searchMap);//searchMap中的数据是前台传过来的
            example.orderBy("createDate").desc();
            //Example.Criteria criteria = example.createCriteria();
            //criteria.orEqualTo("1");
            Page<Order> orderPage = (Page<Order>) orderMapper.selectByExample(example);
            return orderPage;
        }
        return null;
    }

    /**
     * 点击查看
     *
     * @param id
     * @return
     */
    @Override
    public OrderGroup viewAll(String id) {
        //创建实例化对象,公用的
        OrderGroup orderGroup = new OrderGroup();
        //根据前台传过来的订单id查询tb_order表中所有数据
        Order orderList = orderMapper.selectByPrimaryKey(id);
        //Order是OrderGroup中的元素，所以用orderGroup.setOrder(orderList)
        orderGroup.setOrder(orderList);//把tb_order的所有数据封装到orderGroup实例化对象中
        /*订单详情表*/
        OrderDetail orderDetail = new OrderDetail();//创建订单详情表的对象
        orderDetail.setOrderId(id);//把前台传来的id给orderDetail
        List<OrderDetail> orderDetailList = orderDetailMapper.select(orderDetail);
        orderGroup.setOrderDetail(orderDetailList);//查询tb_order_detail所有数据封装到orderGroup中
        /*订单日志表*/
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(id);
        List<OrderLog> orderLogList = orderLogMapper.select(orderLog);
        orderGroup.setOrderLog(orderLogList);
        /*服务商信息*/
        //Store store = new Store();
        String storeId = orderList.getStoreId();
        Store data = subjectFeign.findByOrderStoreId(Long.valueOf(storeId)).getData();
        orderGroup.setStore(data);
        /*车主信息*/
        String carCode = orderList.getCarCode();//获取车牌号
        Car car = carFeign.findByOrderCode(carCode).getData();
        orderGroup.setCar(car);
        return orderGroup;
    }

    /**
     * 查询所有订单
     *
     * @param searchMap
     * @return
     */
    @Override
    public List<Order> findOrders(Map searchMap) {
        //自定义类，封装参数
        Example example = createExample(searchMap);
        //按创建订单的时间降序
        example.orderBy("createDate").desc();
        List<Order> orderList = orderMapper.selectByExample(example);
        return orderList;
    }

    @Override
    public List findMoneyByDate(Map map) throws ParseException {
          //格式转换
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse((String) map.get("date"));
        String storeName = (String) map.get("storeName");
        if (storeName!=null&&!"".equals(storeName)){
            List moneyByStore = orderMapper.findMoneyByStore(parse, storeName);
            return moneyByStore;
        }
        List byDate = orderMapper.findMoneyByDate(parse);
        return byDate;
    }

    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null && (searchMap.size()) > 0) {
            //订单编号
            if (searchMap.get("code") != null && !"".equals(searchMap.get("code"))) {
                criteria.andEqualTo("code", searchMap.get("code"));
            }
            //客户名称
            if (searchMap.get("contact") != null && !"".equals(searchMap.get("contact"))) {
                criteria.andLike("contact", "%" + searchMap.get("contact") + "%");
            }
            //商家名称
            if (searchMap.get("storeName") != null && !"".equals(searchMap.get("storeName"))) {
                criteria.andEqualTo("storeName", "%" + searchMap.get("storeName") + "%");
            }
            //支付状态
            if (searchMap.get("payStatus") != null && !"".equals(searchMap.get("payStatus"))) {
                criteria.andEqualTo("payStatus", searchMap.get("payStatus"));
            }
            //订单状态
            if (searchMap.get("orderStatus") != null && !"".equals(searchMap.get("orderStatus"))) {
                criteria.andEqualTo("orderStatus", searchMap.get("orderStatus"));
            }
            //订单时间（创建日期）
            if (searchMap.get("startTime") != null && !"".equals(searchMap.get("startTime"))) {
                criteria.andGreaterThanOrEqualTo("createDate", searchMap.get("startTime"));
                if (searchMap.get("endTime") != null && !"".equals(searchMap.get("endTime"))) {
                    criteria.andLessThanOrEqualTo("createDate", searchMap.get("endTime"));
                }
            }
        }
        return example;
    }

    /*    *//**
     * 查询车主信息（点击查看）
     *//*
    @Override
    public Map lookAll(String code) {
        Car car = carFeign.findByOrderCode(code).getData();
//        Result orderCode = carFeign.findByOrderCode(code);
//        Object car = orderCode.getData();
//        System.out.println("car = " + car);
        List<Order> orderList = orderMapper.selectAll();//查询tb_order表中所有的数据
        HashMap orderMap = new HashMap<>();//创建map对象

        for (Order order : orderList) {//遍历orderList中的数据，获取所需的数据
            String contactTel = order.getContactTel();//获取客户电话
            String appointmentDate = order.getAppointmentDate();//获取预约时间
            orderMap.put("contact_tel", contactTel);
            orderMap.put("appointment_date", appointmentDate);
        }

        HashMap carMap = new HashMap<>();
//        carMap.put("car", car);
        carMap.put("name", car.getName());*//*车主名称*//*
        carMap.put("code", car.getCode());*//*车牌号*//*
        carMap.put("engine_code", car.getEngineCode());*//*发动机型号*//*
        carMap.put("frame_code", car.getFrameCode());*//*VIN码*//*
        carMap.put("mode", car.getMode());*//*车型*//*
        carMap.put("orderMap", orderMap);*//*客户电话，预约时间*//*
        return carMap;
    }

    *//**
     * 查询操作记录（点击查看）
     *
     * @param id
     * @return
     *//*
    @Override
    public OrderLog findByOrderId(String id) {
        OrderLog byPrimaryKey = orderLogMapper.selectByPrimaryKey(id);//查询tb_order_log表中的所有数据
//        HashMap map = new HashMap<>();//用map封装
//        for (OrderLog orderLog : byPrimaryKey) {//遍历orderList中每个元素
//            map.put("order",orderLog.getHandleTime());
//            map.put("handle_time",orderLog.getDescription());
//            map.put("order_status",orderLog.getOrderStatus());
//            map.put("user_realname",orderLog.getUserRealname());
//        }
//        return map;
        return byPrimaryKey;
    }

    *//**
     * 查询服务商信息（点击查看）
     *
     * @param id
     * @return
     *//*
    @Override
    public Map findByOrderStoreId(Long id) {
        Result<Store> OrderStoreId = subjectFeign.findByOrderStoreId(id);
        Store store = OrderStoreId.getData();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("simple_name", store.getSimpleName());
        map.put("contact_phone", store.getContactPhone());
        map.put("address", store.getAddress());
        return map;
    }*/
}
